package com.alcatel_lucent.osp.action;

import com.alcatel_lucent.osp.service.DaoService;
import com.alcatel_lucent.osp.service.JSONService;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: guoshunw
 * Date: 13-8-20
 * Time: 下午2:14
 */

@ParentPackage("osp-json")

@Result(type = "json", params = {
        "noCache", "true",
        "enableGZIP ", "true",
        "ignoreHierarchy", "false",
        "root", "json",
        "excludeNullProperties", "true",
        "excludeProperties", "request, jsonService, requestMap"
})
public abstract class QueryJSONAction extends BaseAction implements ServletRequestAware {

    private HttpServletRequest request;
    @Autowired
    private JSONService jsonService;
    private JSON json;

    //        Map<String,String[]> requestMap = request.getParameterMap();
    protected Map<String, String> requestMap = new HashMap<String, String>();

    public JSON getJson() {
        return json;
    }

    public void setJson(JSON json) {
        this.json = json;
    }

    /**
     * Sets the HTTP request object in implementing classes.
     *
     * @param request the HTTP request.
     */
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;

        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name = paramNames.nextElement();
            requestMap.put(name, request.getParameter(name));
        }
    }

    protected void populateJSON(String hql, Map<?, ?> param, String countHql, Map<?, ?> countParam) throws JSONException {
        this.setJson(jsonService.getJSON(requestMap, hql, param, countHql, countParam));
    }

    protected Map<String, Object> getGridFilters() {
        String filterStr = requestMap.get("filters");
        if (filterStr == null || filterStr.trim().isEmpty()) return null;
        Map<String, Object> result = new HashMap<String, Object>();
        JSONObject json = JSONObject.fromObject(filterStr);
        JSONArray jsonRules = json.getJSONArray("rules");
        Iterator<JSONObject> iter= jsonRules.iterator();
        while (iter.hasNext()) {
            JSONObject rule = iter.next();
            result.put(rule.getString("field"), rule.getString("data"));
        }
        return result;
    }
}
